<?php

namespace app\admin\model;

use app\admin\validate\Article as ValidateArticle;
use app\admin\model\Tap;
use think\exception\ValidateException;
use think\facade\Session;
use think\Model;

class Article extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
    public function searchTitleAttr($query, $value, $data)
    {
        $query->where('title', 'like', '%' . $value . '%');
    }

    public function searchCreateTimeAttr($query, $value, $data)
    {
        $query->whereBetweenTime('create_time', $value[0], $value[1]);
    }
    public function searchContentAttr($query, $value, $data)
    {
        $query->where('content', 'like', '%' . $value . '%');
    }
    // 文章添加 -> 参数验证
    static public function handleParam(array $param)
    {
        if (isset($param['type']) && $param['type'] != 3 && $param['type'] != 2) {
            unset($param['score']);
        }
        if ($param['type'] == 3 && empty(@$param['comType'])) {
            return '请选择文章评论的显示方式';
        }

        try {
            validate(ValidateArticle::class)->check($param);

            // 是否存在分类
            $checkCate = (new Category)->isThree($param['category_id']);

            if ($checkCate != 1)   return $checkCate;
            // @param type 2付费 3 悬赏
            $tapId = !empty($param['tap_id']) ? Tap::handleSpliceToArr($param['tap_id']) : '';
            // 是否有这个用户
            $hasUser = User::findOrEmpty($param['user_id'])->isEmpty();
            if ($hasUser) return '不存在该用户';
            $param['content'] = remove_xss(str_replace("<p><br/></p>", '', $param['content']));
            $param['tap_id'] = $tapId;
            // $param['status'] = 1;
            // 更新文章判断
            if (isset($param['id'])) {
                $artData = self::find($param['id']);
                // 如果不是悬赏文章或为悬赏文章 需添加数据
                if ($artData['type'] != 3 && $param['type'] == 3) {
                    if (ArtAdopt::where(['article_id' => $param['id']])->findOrEmpty()->isEmpty()) {
                        ArtAdopt::create(['author_id' => $artData->user_id, 'type' => $param['comType'], 'article_id' => $param['id']]);
                    }
                }
            }
            return $param;
        } catch (ValidateException $e) {
            return $e->getError();
        }
    }
    static public function list($param = [])
    {
        $limit = !array_key_exists('limit', $param) ? '10' : $param['limit'];
        if (@$param['type'] == 'search') {
            if (isset($param['where'])) $where = $param;
            // 文章搜索
            $title = @$param['title'];
            $content = @$param['content'];
            $begin_time = @$param['begin_time'] ?? '1970-1-1';
            $end_time = @$param['end_time'] ?? date('Y-m-d', time());
            if (!empty($title) && empty($content)) {
                $list = self::where('title', 'like', '%' . $title . '%')->order('status asc ,id desc,sort asc');
            } else if (empty($title) && !empty($content)) {
                $list = self::where('content', 'like', '%' . $content . '%')->order('status asc ,id desc,sort asc');
            } else {
                $list = self::withSearch(['title', 'content', 'create_time'], [
                    'title'     =>   $title,
                    'content' => $content,
                    'create_time'    =>  [$begin_time, $end_time],
                ])->order('status asc ,id desc,sort asc');
            }
        } else {
            $list = self::order('status asc ,id desc,sort asc');
            if (array_key_exists('pid', $param)) {
                $list = self::where('category_id',$param['pid'])->order('status asc ,id desc,sort asc');
            }
        }
        if (array_key_exists('where', $param)) {
            $key = array_keys($param['where']);
            // 判断是否为热度文章
            if ($key[0] == 'heat') {
                $list->where('heat', '>', $param['where']['heat']);
            } else {
                $list->where($param['where']);
            }
        }
        $list = $list->paginate($limit);
        foreach ($list as $k => $v) {
            $list[$k]['user_id'] = User::where('id', $v['user_id'])->value('username');
            if ($v['tap_id'] != '') $v['tap_id'] = (new Tap())->get($v['id']);
            else $v['tap_id'] = '无,';
        }
        $data = [
            "code" => 0,
            'msg' => '',
            'count' => $list->total(),
            'data' => $list
        ];
        return $data;
    }
    static public function publishList()
    {
        $list = self::column('create_time');
        $data = [];
        for ($i = 1; $i <= 7; $i++) {
            $j = 0;
            foreach ($list as $k => $v) {
                $today = date('w', time());
                $t = ($today == 0 ? 7 : $today) - $i;
                if($t == 0)
                {
                    $t = time();
                }else if($t > 0){
                    $t = strtotime(date('Y-m-d',strtotime("-$t day")));
                }else{
                    $t = 0;
                }
                if (date('Y-m-d',$t) == date('Y-m-d', $v)) {
                    $j++;
                }else if($t == 0){
                    $j = 0;
                }
            }
            $data[$i] = $j;
        }
        $data = implode(',', $data);
        $data = '[' . $data . ']';
        return $data;
    }
    // // 首页的文章发布趋势
    // static public function publishList()
    // {
    //     $list = self::column('create_time');
    //     $arr = '';
    //     for ($i = 0; $i <= 6; $i++) {
    //         $arr .= self::cumpate($list, $i)  . ',';
    //     }
    //     $arr = substr($arr, 0, strlen($arr) - 1);
    //     return '[' . $arr . ']';
    // }
    // // 首页的文章发布趋势 计算周一到周日的数据
    // static public function cumpate($list, $time)
    // {
    //     $i = 0;
    //     foreach ($list as $k => $v) {
    //         if (date('w', $v) == $time) {
    //             $i++;
    //         }
    //     }
    //     return $i;
    // }
    public function profile()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
    public function collect()
    {
        return $this->hasMany(Collect::class);
    }
    static public function lists($data = [])
    {

        if (array_key_exists('list', $data)) $list = $data['list'];
        else {
            $limit = isset($data['limit']) ? $data['limit'] : 10;
            $pageRes = array_key_exists('category_id', $data) ? ['list_rows' => $limit, 'query' => ['id' => $data['category_id']]] : $limit;
            $list = self::where($data)->order('id desc')->paginate($pageRes);
        }
        $todayNum = 0;
        foreach ($list as $key => $item) {
            if (date('d', strtotime($item['create_time'])) == date('d', time())) $todayNum++;
            $list[$key]['commentCount'] = Comment::where('article_id', $item['id'])->count();
            $list[$key]['collectCount'] = Collect::where('article_id', $item['id'])->count();
            $list[$key]['username'] = User::where('id', $item['user_id'])->value('username');
            $list[$key]['headIcon'] = User::where('id', $item['user_id'])->value('head_icon');
            if ($list[$key]->tap_id != '') $list[$key]['tapList'] = (new Tap)->get($item['id']);
            else $list[$key]['tapList'] = [];
        }
        $data = [
            'list' => $list,
            'totalNum' => $list->total(),
            'todayNum' => $todayNum
        ];
        return $data;
    }

    public function del($art_id)
    {
        $hasArt = $this->findOrEmpty($art_id)->isEmpty();
        if ($hasArt) return error('文章不存在');
        $artCtn = $this->find($art_id)->content;
        // 图片删除
        $imgNum = preg_match_all("/.*<img src=\"(.*)\".*/", $artCtn, $img);
        if ($imgNum > 0) {
            $imgArr = [];
            foreach ($img[1] as $k => $v) {
                array_push($imgArr, strstr($v, '" alt=', true));
            }
            foreach ($imgArr as $j) {
                $path = app()->getRootPath() . 'public' . $j;
                if (file_exists($path))
                    unlink($path);
            }
        }
        $article = Article::with('comments')->find($art_id);
        if ($article) {
            $res = $article->together(['comments'])->delete();
        }
        $res = Article::destroy($art_id);
        if ($res) return 1;
    }
}
